package com.example.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.boot.mapper.RoleMapper;
import com.example.boot.mapper.UserMapper;
import com.example.boot.mapper.UserRoleMapper;
import com.example.boot.pojo.entity.User;
import com.example.boot.pojo.entity.UserRole;
import com.example.boot.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * @description:
 * @author: mhpy
 * @date 2022/8/6 22:03
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;

    @Override
    public Page<User> getAllUser(Integer current,Integer size) {
        return userMapper.selectPage(new Page<>(current,size),null);
    }

    @Override
    public User getUserInfo(String name) {
        return userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getName,name));
    }

    @Override
    public String[] getCurrentUserRoles(Integer id) {
        UserRole userRole = userRoleMapper.selectOne(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, id));
        if (userRole == null){
            return new String[]{};
        }
        Integer roleId = userRole.getRoleId();
        String roleName = roleMapper.selectById(roleId).getRoleName();
        return new String[]{roleName};
    }

    @Override
    public void assignmentRole(Integer userId,Integer roleId) {
        UserRole userRole = userRoleMapper.selectOne(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId).eq(UserRole::getRoleId, roleId));
        if (ObjectUtils.isEmpty(userRole)){
            userRoleMapper.insert(new UserRole(userId,roleId));
        }
    }
}
